package utils

import (
	"fmt"
	"lark/src/ast"
	"lark/src/object"
)

var (
	NULL  = &object.Null{}
	TRUE  = &object.Boolean{Value: true}
	FALSE = &object.Boolean{Value: false}
)

// 解析语法树
func ParserSyntaxTrees(node ast.Node, env *object.Environment) object.Object {
	switch node := node.(type) {
	case *ast.Program:
		// fmt.Println("Program:", node, "\n")
		return evalProgram(node, env)
	/* case *ast.LetStatement:
	// fmt.Println("LetStatement:", node.Value, "\n")
	val := ParserSyntaxTrees(node.Value, env)
	//放到符号表中
	env.Set(node.Name.Value, val)
	//标识符
	return evalIdentifier(node.Name, env) */
	case *ast.Identifier:
		// fmt.Println("Identifier:", node, "\n")
		//标识符
		// return evalIdentifier(node, env)
		//字符串
		return &object.String{Value: node.Value}
	case *ast.Boolean:
		return nativeBoolToBooleanObject(node.Value)
	case *ast.IntegerLiteral:
		//整数
		return &object.Integer{Value: node.Value}
	case *ast.FloatLiteral:
		//浮点数
		return &object.Float{Value: node.Value}
	case *ast.StringLiteral:
		// fmt.Println("StringLiteral:", node)
		//字符串
		return &object.String{Value: node.Value}
	case *ast.ExpressionStatement:
		// fmt.Println("ExpressionStatement11:", node)
		return ParserSyntaxTrees(node.Expression, env)
	case *ast.PrefixExpression:
		// fmt.Println("PrefixExpression:", node)
		//前缀表达式
		right := ParserSyntaxTrees(node.Right, env)
		return evalPrefixExpression(node.Operator, right)

	case *ast.ArrayLiteral:
		// fmt.Println("ArrayLiteral:", node, "\n")
		elements := evalExpressions(node.Elements, env)
		if len(elements) == 1 && isError(elements[0]) {
			return elements[0]
		}
		return &object.Array{Elements: elements}
	case *ast.IndexExpression:
		left := ParserSyntaxTrees(node.Left, env)
		if isError(left) {
			return left
		}
		index := ParserSyntaxTrees(node.Index, env)
		if isError(index) {
			return index
		}
		return evalIndexExpression(left, index)
	case *ast.HashLiteral:
		return evalHashLiteral(node, env)
	}
	return nil
}

func evalProgram(program *ast.Program, env *object.Environment) object.Object {
	var result object.Object

	for _, statement := range program.Statements {
		result = ParserSyntaxTrees(statement, env)
	}

	return result
}

// 标识符
func evalIdentifier(node *ast.Identifier, env *object.Environment) object.Object {
	//获取符号表中的标识符
	if val, ok := env.Get(node.Value); ok {
		return val.Value
	}
	return newError("identifier not found: " + node.Value)
}
func nativeBoolToBooleanObject(input bool) *object.Boolean {
	if input {
		return TRUE
	}
	return FALSE
}

// 前缀表达式
func evalPrefixExpression(operator string, right object.Object) object.Object {
	switch operator {
	case "!":
		//逻辑运算符取返
		return evalBangOperatorExpression(right)
	case "-":
		return evalMinusPrefixOperatorExpression(right)
	default:
		return newError("未知运算符: %s%s", operator, right.Type())
	}
}

func evalBangOperatorExpression(right object.Object) object.Object {
	switch right {
	case TRUE:
		return FALSE
	case FALSE:
		return TRUE
	case NULL:
		return TRUE
	default:
		return FALSE
	}
}

func evalMinusPrefixOperatorExpression(right object.Object) object.Object {
	if right.Type() != object.INTEGER_OBJ {
		return newError("unknown operator: -%s", right.Type())
	}

	value := right.(*object.Integer).Value
	return &object.Integer{Value: -value}
}
func evalExpressions(exps []ast.Expression, env *object.Environment) []object.Object {
	var result []object.Object

	for _, e := range exps {
		evaluated := ParserSyntaxTrees(e, env)
		/* if isError(evaluated) {
			return []object.Object{evaluated}
		} */
		result = append(result, evaluated)
	}

	return result
}
func evalIndexExpression(left, index object.Object) object.Object {
	switch {
	case left.Type() == object.ARRAY_OBJ && index.Type() == object.INTEGER_OBJ:
		return evalArrayIndexExpression(left, index)
	case left.Type() == object.HASH_OBJ:
		return evalHashIndexExpression(left, index)
	default:
		return newError("index operator not supported: %s", left.Type())
	}
}

func evalArrayIndexExpression(array, index object.Object) object.Object {
	arrayObject := array.(*object.Array)
	idx := index.(*object.Integer).Value
	max := int64(len(arrayObject.Elements) - 1)

	if idx < 0 || idx > max {
		return NULL
	}

	return arrayObject.Elements[idx]
}

func evalHashLiteral(node *ast.HashLiteral, env *object.Environment) object.Object {
	pairs := make(map[object.HashKey]object.HashPair)

	for keyNode, valueNode := range node.Pairs {
		key := ParserSyntaxTrees(keyNode, env)
		if isError(key) {
			return key
		}
		hashKey, ok := key.(object.Hashable)
		if !ok {
			return newError("unusable as hash key: %s", key.Type())
		}

		value := ParserSyntaxTrees(valueNode, env)
		if isError(value) {
			return value
		}

		hashed := hashKey.HashKey()
		pairs[hashed] = object.HashPair{Key: key, Value: value}
	}

	return &object.Hash{Pairs: pairs}
}

func evalHashIndexExpression(hash, index object.Object) object.Object {
	hashObject := hash.(*object.Hash)

	key, ok := index.(object.Hashable)
	if !ok {
		return newError("unusable as hash key: %s", index.Type())
	}

	pair, ok := hashObject.Pairs[key.HashKey()]
	if !ok {
		return NULL
	}

	return pair.Value
}

// 抛出错误
func newError(format string, a ...interface{}) *object.Error {
	return &object.Error{Message: fmt.Sprintf(format, a...)}
}
func isError(obj object.Object) bool {
	if obj != nil {
		return obj.Type() == object.ERROR_OBJ
	}
	return false
}
